package com.yy.device.boot.websocket;

import com.yy.device.config.ExecutorServiceConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WebSocketServer {

    private int port;

    public WebSocketServer(int port) {
        this.port = port;
        connect();
    }

    private void connect() {
        ExecutorServiceConfig.executorService.execute(() -> {
            NioEventLoopGroup boss = new NioEventLoopGroup();
            NioEventLoopGroup work = new NioEventLoopGroup();
            try {
                ServerBootstrap bootstrap = new ServerBootstrap();
                bootstrap.group(boss, work);
                bootstrap.channel(NioServerSocketChannel.class);
                bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new HttpServerCodec())
                                .addLast(new HttpObjectAggregator(65536))
                                .addLast(new ChunkedWriteHandler())
                                .addLast(new WebSocketServerCompressionHandler())
//                                .addLast(new WebSocketServerProtocolHandler("/"))
                                .addLast(new WebSocketHandler());
                    }
                });
                Channel channel = bootstrap.bind(this.port).sync().channel();
                log.info("webSocket服务器启动成功 port = " + port);
                channel.closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.info("运行出错：" + e);
            } finally {
                boss.shutdownGracefully();
                work.shutdownGracefully();
                log.info("websocket服务器已关闭");
            }
        });

    }
}
